package com.javafactroy.kunlong.bip.icp.message.data.netty.handler.client;


import com.javafactroy.kunlong.bip.icp.message.data.netty.codec.AppByte2MsgDecoder;
import com.javafactroy.kunlong.bip.icp.message.data.netty.codec.AppMsg2ByteEncoder;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.EventExecutor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.javafactroy.kunlong.bip.icp.message.base.iface.IMessage;


@Component
@Data
@Scope("prototype")
public class NettyClientHandlerInitilizer extends ChannelInitializer<Channel> {
    String uuid;
    /**
     * @Fields clientHandler : 客户端处理
     */
    @Autowired
    private NettyClientHandler clientHandler;

    public void setPromise(EventExecutor executor){
        getClientHandler().setPromise(new DefaultPromise<>(executor));

    }

    public DefaultPromise<IMessage> getPromise (){
        return getClientHandler().getPromise() ;

    }
    @Override
    protected void initChannel(Channel ch) throws Exception {
        clientHandler.setUuid(uuid);
        ChannelPipeline pipeline = ch.pipeline();
        if (pipeline.get(DataClientLengthFieldDecoder.class) == null) {
            pipeline.addLast(
                    new DataClientLengthFieldDecoder(),
                    new AppByte2MsgDecoder(),
                    new AppMsg2ByteEncoder()).addLast(clientHandler);
        }
    }

}
